package com.dongbing.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

public class NettyServerSelectorNonClogging {

    /**
     * 处理半包
     * 存在的问题 ByteBuffer 不能动态调整 每一行数据没有 \n 的时候不能截止
     */
    public static void doLineSplit(ByteBuffer buffer) {
        // 开启读模式
        buffer.flip();
        // 开始处里buffer中的数据
        for (int i = 0; i < buffer.limit(); i++) {
            if (buffer.get(i) == '\n') {
                int length = i + 1 - buffer.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                for (int j = 0; j < length; j++) {
                    target.put(buffer.get());
                }

                target.flip();

                System.out.println(StandardCharsets.UTF_8.decode(target));
            }

        }

        buffer.compact();
    }

    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 设置没有客户端的时候 不堵塞
        serverSocketChannel.configureBlocking(false);
        // 绑定端口
        serverSocketChannel.bind(new InetSocketAddress(8080));
        // 设置监视器
        Selector selector = Selector.open();
        // 设置监视器 要监视谁
        SelectionKey selectionKey = serverSocketChannel.register(selector, 0, null);
        // 监控 OP_ACCEPT
        selectionKey.interestOps(SelectionKey.OP_ACCEPT);
        // 循环写死
        while (true) {
            // 开始监控 ServerSocketChannel
            selector.select();
            // selectedKeys 是每一次变动的 Channel 都会放到这个里面来
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                // 这里要注意 我们获取到那个那个变动了 那么就
                iterator.remove();
                if (key.isAcceptable()) {
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel socketChannel = channel.accept();
                    socketChannel.configureBlocking(false);
                    // 创建缓冲区
                    ByteBuffer buffer = ByteBuffer.allocate(4);
                    SelectionKey register = socketChannel.register(selector, 0, buffer);
                    // 这些socketChannel只专注于读取
                    register.interestOps(SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    try {
                        // 走到这个地方就一定是写操作
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = (ByteBuffer) key.attachment();
                        int read = channel.read(buffer);
                        if (read == -1) {
                            key.cancel();
                        } else {
                            doLineSplit(buffer);
                            if (buffer.position() == buffer.limit()) {
                                // 空间扩大
                                ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity() * 2);
                                // 转移数据
                                buffer.flip();
                                newBuffer.put(buffer);
                                // 重新绑定一下
                                key.attach(newBuffer);
                            }
                        }
                    } catch (Exception e) {
                        // 异常直接提示处理完成
                        key.cancel();
                    }
                }
            }
        }
    }
}
